package com.learn.hibernatevalidator.chapter12.getterselectionstrategy;

import org.hibernate.validator.spi.properties.ConstrainableExecutable;
import org.hibernate.validator.spi.properties.GetterPropertySelectionStrategy;

import java.util.*;
import java.util.stream.Collectors;

import java.lang.reflect.Method;


/**
 * @author: liyf
 * @create: 2025-02-05 22:03
 **/
public class FluentGetterPropertySelectionStrategy implements GetterPropertySelectionStrategy {

    private final Set<String> methodNamesToIgnore;

    public FluentGetterPropertySelectionStrategy() {
        // we will ignore all the method names coming from Object
        this.methodNamesToIgnore = Arrays.stream(Object.class.getDeclaredMethods())
                .map(Method::getName)
                .collect(Collectors.toSet());
    }

    @Override
    public Optional<String> getProperty(ConstrainableExecutable executable) {
        if (methodNamesToIgnore.contains(executable.getName())
                || executable.getReturnType() == void.class
                || executable.getParameterTypes().length > 0) {
            return Optional.empty();
        }

        return Optional.of(executable.getName());
    }

    @Override
    public List<String> getGetterMethodNameCandidates(String propertyName) {
        // As method name == property name, there always is just one possible name for a method
        return Collections.singletonList(propertyName);
    }
}